import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { RoomEntity } from './entities/room.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { TalkEntity } from './entities/talk.entity';
import * as moment from 'moment';

@Injectable()
export class TalkService {
  constructor(
    @InjectRepository(RoomEntity)
    private readonly roomRepository: Repository<RoomEntity>,

    @InjectRepository(TalkEntity)
    private readonly talkRepository: Repository<TalkEntity>,
  ) {}
  // 创建房间
  async create(room: RoomEntity) {
    await this.isRoomExist(room.roomName);
    return this.roomRepository.save(room);
  }
  // 删除房间
  remove(id: number) {
    return this.roomRepository.delete(id);
  }
  // 更新房间信息
  async update(room: RoomEntity) {
    const id = room.id;
    return await this.roomRepository.update(id, room);
  }
  // 获取房间列表 可分页
  async getRoomList(page: number, limit: number) {
    const skip = (page - 1) * limit;
    const res = await this.roomRepository.find({
      skip,
      take: limit,
    });

    const resTemp = res.map((item) => {
      return {
        ...item,
        createTime: moment(item.createTime).format('yyyy-MM-DD HH:mm:ss'),
      };
    });
    console.log(resTemp);
    Object.assign(res, resTemp);
    const total = await this.roomRepository.count();
    return {
      data: res,
      total,
      page,
      limit,
    };
  }

  // 获取房间在线人员列表
  async getOnlineUserList(roomName: string) {
    const room = await this.roomRepository.findOne({
      where: { roomName },
    });
    const res = !!room.onlineUsers ? JSON.parse(room.onlineUsers) : [];
    return res;
  }
  async getTalkByRoomName(roomName: string) {
    // 判断是否该房间不存在
    await this.isRoomNoExist(roomName);
    // 根据roomName查询room的id
    const room = await this.roomRepository.findOne({
      where: { roomName },
    });
    const talkList = await this.talkRepository.find({
      where: { roomId: room.id },
    });
    // console.log(talkList);
    const res = talkList.map((item) => {
      return JSON.parse(item.msgData);
    });
    return res;
  }

  async isRoomExist(roomName: string) {
    const exists = await this.roomRepository.findOne({
      where: { roomName },
    });
    if (exists) {
      throw new HttpException(
        { message: 'roomName is exist' },
        HttpStatus.BAD_REQUEST,
      );
    }
  }

  async isRoomNoExist(roomName: string) {
    const exists = await this.roomRepository.findOne({
      where: { roomName },
    });
    if (!exists) {
      throw new HttpException(
        { message: 'roomName is not exist' },
        HttpStatus.BAD_REQUEST,
      );
    }
  }
  findAll() {
    return `This action returns all talk`;
  }

  findOne(id: number) {
    return `This action returns a #${id} talk`;
  }
}
